package org.mbds.wolf.android.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class FileUtilities {
	
	/**
	 * getFileFromAssets
	 * @param context
	 * @return
	 * @throws IOException
	 */
	public static File getFileFromAssets(final Context context, final String fileName) throws IOException {
		Resources resources = context.getResources();
		AssetManager assetManager = resources.getAssets();
		// Read from the /assets directory
		InputStream inputStream = assetManager.open(fileName);
		File tempFile = File.createTempFile(fileName, ".tmp");
		tempFile.deleteOnExit();
		OutputStream out=new FileOutputStream(tempFile);
		byte buf[]=new byte[1024];
		int len;
		while((len=inputStream.read(buf))>0)
			out.write(buf,0,len);
		out.close();
		inputStream.close();
		return tempFile;
	}

	
	
	public synchronized static Bitmap loadImage(String fn)
	// load the image stored in fn in images/
	{
		Bitmap bmp = null;
		System.out.println(fn);
		String file = fn;
		bmp = BitmapFactory.decodeFile(file);
		return bmp;
	}
	
	public static boolean deleteFileFromExternalStorage(String pathFile) {
		boolean deleted = false;
		try {
	        File datafile = new File(Environment.getExternalStorageDirectory(), pathFile);
	        deleted = datafile.delete();
		} catch (Exception e) {
	    	Log.w("LOG","Failed to dalete file: "+pathFile);
		}
		return deleted;
	}
	
	public static void saveDataToExternalStorage(String pathFile, String data) {
		try{		
			File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
		    if (file.canWrite()){
		        File datafile = new File(file, pathFile);
		        RandomAccessFile raf = new RandomAccessFile(datafile, "rw");
		        if (raf.length()>0)
		        	raf.seek(raf.length()-1);
		        raf.writeBytes(data + "\r\n");
		        raf.close();
		    }
		    else {
		    	Log.w("LOG","Could not write log on the SD card");
		    }
		} catch (IOException e) {
	    	Log.w("LOG","Failed to save log in local file: "+pathFile);
    	}	
	}
	
    public static String getFileContents(final File file) throws IOException {
        final InputStream inputStream = new FileInputStream(file);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        
        final StringBuilder stringBuilder = new StringBuilder();
        
        boolean done = false;
        
        while (!done) {
            final String line = reader.readLine();
            done = (line == null);
            
            if (line != null) {
                stringBuilder.append(line);
            }
        }
        
        reader.close();
        inputStream.close();
        
        return stringBuilder.toString();
    }
    
	public static void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1)
        {
        	out.write(buffer, 0, read);
        }
    }

	/*******************************/
    /* Check if a directory exists */
    /*******************************/
    public static boolean checkDirectory(String directory, Context ctx)
    {
    	File dir_geoloc = new File(directory);
        if(dir_geoloc.exists()==false || dir_geoloc.isDirectory()==false)
        {
        	return false;
        }
        return true;
    }
    
    /************************************************/
    /* Check if a file exists or not on the SD card */
    /************************************************/
    public static boolean checkFileExternalStorage(String filename, Context ctx, String path)
    {
    	File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + filename);
        if(!file.exists() || !file.isFile())
        {
        	FileUtilities.saveLogExternalStorage("Missing file", filename, 2, path);
        	return false;
        }
        return true;
    }
    
    /*********************************/
    /* Check if a SD card is present */
    /*********************************/
    public static boolean isExternalStoragePresent()
    {
    	return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}	


    
	public static void saveLogExternalStorage(String title, String data, int logType, String pathFile) {
    	switch (logType){
    	case 0:
    		Log.d(title,data);
    		break;
    	case 1:
    		Log.i(title,data);
    		break;
    	case 2:
    		Log.e(title,data);
    		break;
    	case 3:
    		Log.w(title,data);
    		break;
    	}
        if (1==1) {

			try{		
				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
			    if (file.canWrite()){
			        File gpxfile = new File(file, pathFile);
			        RandomAccessFile raf = new RandomAccessFile(gpxfile, "rw");
			        if (raf.length()>0)
			        	raf.seek(raf.length()-1);
			        raf.writeBytes(data + "\r\n");
			        raf.close();
			    }
			    else {
			    	Log.w("LOG","Could not write log on the SD card");
			    }
			} catch (IOException e) {
		    	Log.w("LOG","Failed to save log in local file");
	    	}	
        }
	}
	
	public static InputStream getInputStreamFromUrl(String url) {
	    URL u;
		try {
			u = new URL(url);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return null;
		}     
	    HttpURLConnection c;
		try {
			c = (HttpURLConnection) u.openConnection();
		} catch (IOException e1) {
			e1.printStackTrace();
			return null;
		}     
	    try {
			c.setRequestMethod("GET");
		} catch (ProtocolException e) {
			e.printStackTrace();
			return null;
		}     
	    c.setDoOutput(true);     
	    try {
			c.connect();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}     
	    InputStream in;
		try {
			in = c.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}      
	    return in; 
	}
}

